import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv, ConfigEnv, UserConfig } from 'vite'
import { resolve } from 'path'
import { createVitePlugin, createViteProxy, wrapperEnv } from './vite.helper'

export const pathResolve = (dir: string) => {
  return resolve(process.cwd(), '.', dir)
}

// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const root = fileURLToPath(new URL('.', import.meta.url))
  const env = loadEnv(mode, root)
  const viteEnv = wrapperEnv(env as unknown as ViteEnv)
  const { VITE_APP_DROP_CONSOLE, VITE_APP_PORT, VITE_APP_PROXY } = viteEnv

  // 输出文件夹
  const OUTPUT_DIR = 'business-related'
  const ASSETS_DIR = 'static'

  return {
    plugins: createVitePlugin(),
    base: env.VITE_APP_BASE,
    server: {
      host: true,
      port: VITE_APP_PORT,
      proxy: createViteProxy(VITE_APP_PROXY)
    },
    resolve: {
      alias: [
        {
          find: '@',
          replacement: pathResolve('src') + '/'
        }
      ],
      // 忽略后缀名的配置选项, 添加 .vue 选项时要记得原本默认忽略的选项也要手动写入
      extensions: ['.vue', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.json']
    },
    // 打包
    build: {
      target: 'es2015',
      outDir: OUTPUT_DIR,
      assetsDir: ASSETS_DIR,
      terserOptions: {
        compress: {
          keep_infinity: true,
          drop_console: VITE_APP_DROP_CONSOLE
        }
      },
      minify: 'terser',
      chunkSizeWarningLimit: 2000
    }
  }
})
